from django.shortcuts import render
from django import http
import json, base64, pickle
from django.views import View
from goods.models import SKU
from django_redis import get_redis_connection
from utils.response_code import RET, error_map


class CartView(View):
    """用户购物车"""

    def get(self, request):
        if request.user.is_authenticated:
            # 获取redis数据
            redis_con = get_redis_connection('carts')
            redis_cart = redis_con.hgetall('carts_user_%s' % request.user.id)
            cart_selected = redis_con.smembers('selected_user_%s' % request.user.id)
            # 将redis中的数据构造成跟cookie中的格式一致，方便统一查询
            cart_dict = {}
            for sku_id, count in redis_cart.items():
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in cart_selected
                }
        else:
            # 用户未登录查询购物车
            cart = request.COOKIE.get('cart')
            if cart:
                cart_dict = pickle.loads(base64.b64decode(cart.decode()))
            else:
                cart_dict = {}
        # 构造购物车渲染数据
        sku_ids = cart_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)  # 获取所有商品queryset对象
        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image_url,
                'price': str(sku.price),  # 取出'10.2'，方便json解析
                'count': cart_dict.get(sku.id).get('count'),
                'amount': str(sku.price * cart_dict.get(sku.id).get('count')),
                'selected': str(cart_dict.get(sku.id).get('selected')),  # 将 True转换成'True' 方便json解析
            })

    def post(self, request):
        """添加购物车"""
        # 1. 获取参数
        dict_data = json.loads(request.body.decode())
        sku_id = dict_data.get('sku_id')
        count = dict_data.get('count')
        selected = dict_data.get("selected", True)
        user = request.user
        # 2.效验参数
        if not all([sku_id, count]):
            return http.HttpResponseForbidden('参数不全')
        # 3.判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return http.HttpResponseForbidden('参数count有误')
        # 4. 判断商品是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('商品不存在')
        # 5. 判断库存是否够
        if count > sku.stock:
            return http.HttpResponseForbidden('库存不够，库存只剩下{}个。'.format(sku.stock))
        # 判断selected 是都是bool值
        # if selected:
        #     if not isinstance(selected, bool):
        #         return http.HttpResponseForbidden('参数selected有误')
        # 6.判断用户登录状态
        if user.is_authenticated:
            # 用户登录购物车数据存储redis
            redis_con = get_redis_connection('carts')
            redis_con.hincrby('carts_user_%s' % user.id, sku_id, count)
            if selected:
                redis_con.sadd('selected_user_%s' % user.id, sku_id)
            return http.JsonResponse({'code': RET.OK, 'msg': error_map[RET.OK]})
        else:
            # 未登录购物车数据存储cookie浏览器中,先获取购物车数据
            cookie_cart = request.COOKIES.get('carts')
            if cookie_cart:
                cart_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))
            else:
                cart_dict = {}
            # 判断要加入购物车的商品是否已经在购物车中,如有相同商品，累加求和，反之，直接赋值
            if sku_id in cart_dict:
                count += cart_dict[sku_id].get('count', 0)
            # 设置新的数据
            cart_dict[sku_id] = {'count': count, 'selected': selected}
            # 加密编码
            cart_dict = base64.b64encode(pickle.dumps(cart_dict)).decode()
            # 设置cookie，返回响应。
            response = http.JsonResponse({'code': RET.OK, 'msg': error_map[RET.OK]})
            response.set_cookie('carts', cart_dict)

            return response
